const { exec } = require('child_process');
require('dotenv').config({ path: '../.env' });

const PORT = process.env.VUE_APP_PORT || process.env.PORT || 8080;

function killPort() {
  if (process.platform === 'win32') {
    // Windows平台
    const command = `netstat -ano | findstr :${PORT} | findstr LISTENING`;
    
    exec(command, (error, stdout) => {
      if (error || !stdout) {
        console.log(`No process found using port ${PORT}`);
        process.exit(0);
      }
      
      const lines = stdout.trim().split('\n');
      if (lines.length > 0) {
        const parts = lines[0].trim().split(/\s+/);
        const pid = parts[parts.length - 1];
        
        exec(`taskkill /PID ${pid} /F`, (killError) => {
          if (killError) {
            console.log(`Failed to kill process ${pid}`);
          } else {
            console.log(`Successfully killed process ${pid} using port ${PORT}`);
          }
          process.exit(0);
        });
      }
    });
  } else {
    // Unix-like系统 (macOS, Linux)
    const command = `lsof -ti:${PORT}`;
    
    exec(command, (error, stdout) => {
      if (error || !stdout) {
        console.log(`No process found using port ${PORT}`);
        process.exit(0);
      }
      
      const pid = stdout.trim();
      exec(`kill -9 ${pid}`, (killError) => {
        if (killError) {
          console.log(`Failed to kill process ${pid}`);
        } else {
          console.log(`Successfully killed process ${pid} using port ${PORT}`);
        }
        process.exit(0);
      });
    });
  }
}

killPort();